package com.yaoxuguang.concurrence.synchronizedpackage.deadLock;

import java.util.concurrent.TimeUnit;

/**
 * @author yaoxuguang
 * @Title: yao-interview
 * @Package com.yaoxuguang.concurrence.synchronizedpackage.deadLock
 * @Description: 多线程死锁
 * @date 2018年12月18日15:06
 */
public class DeadLockDemo implements Runnable{
    private String username;

    Object lock1 = new Object();
    Object lock2 = new Object();

    public void setFlag(String username){
        this.username = username;
    }

    @Override
    public void run() {
        if("a".equals(username.trim())){
            synchronized (lock1){
                try {
                    System.out.println("username="+username);
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println("按lock1->lock2代码顺序执行...");
                }
            }
        }

        if("b".equals(username.trim())){
            synchronized (lock2){
                try {
                    System.out.println("username="+username);
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println("按lock2->lock1代码顺序执行...");
                }
            }
        }
    }
}
